package com.traitswu.websocket.dmxlog.core;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import org.slf4j.LoggerFactory;

import static ch.qos.logback.core.CoreConstants.CODES_URL;

/**
 * Created by xiaoquan on 17-5-26.
 */
public class DmxAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private final DmxLogWebSocketPipe pipe = DmxLogWebSocketPipe.getInstance();
    protected Encoder<ILoggingEvent> encoder;


    @Override
    protected void append(ILoggingEvent eventObject) {
        byte[] bytes = encoder.encode(eventObject);
        pipe.write(eventObject.getLoggerName(), bytes);

    }


    public void setLayout(Layout<ILoggingEvent> layout) {
        addWarn("This appender no longer admits a layout as a sub-component, set an encoder instead.");
        addWarn("To ensure compatibility, wrapping your layout in LayoutWrappingEncoder.");
        addWarn("See also " + CODES_URL + "#layoutInsteadOfEncoder for details");
        LayoutWrappingEncoder<ILoggingEvent> lwe = new LayoutWrappingEncoder<ILoggingEvent>();
        lwe.setLayout(layout);
        lwe.setContext(context);
        this.encoder = lwe;
    }

    public void setEncoder(Encoder<ILoggingEvent> encoder) {
        this.encoder = encoder;
    }



}
